package util

import (
	"encoding/json"
	"io"
	"net/http"
	"net/url"
	"strings"
	"time"
)

// post请求
func HttpPost(allUrl string, signMap map[string]string, headerTag int, data any) ([]byte, error) {
	var payload *strings.Reader
	if headerTag == 0 {
		if dataStr, ok := data.(string); ok {
			payload = strings.NewReader(dataStr)
		} else {
			params, _ := json.Marshal(data)
			payload = strings.NewReader(string(params))
		}
	} else {
		newData := data.(map[string]string)
		postValue := url.Values{}
		for k, v := range newData {
			postValue.Add(k, v)
		}
		payload = strings.NewReader(postValue.Encode())
	}
	req, err := http.NewRequest("POST", allUrl, payload)
	if err != nil {
		return nil, err
	}
	//设置header
	if headerTag == 0 {
		req.Header.Add("Content-Type", "application/json")
	} else {
		req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	}
	req.Header.Add("Cache-Control", "no-cache")

	resp, err := (&http.Client{Timeout: 30 * time.Second}).Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	respByte, err := io.ReadAll(resp.Body)
	return respByte, err
}

// get请求
func HttpGet(url string, signMap map[string]string, headerTag int) ([]byte, error) {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	//设置header
	if headerTag == 0 {
		req.Header.Add("Content-Type", "application/json")
	} else {
		req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	}

	resp, err := (&http.Client{Timeout: 30 * time.Second}).Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)
	return body, err
}
